<?php
  /**
   * iJConfig
   *
   * The iJConfig class provides config loading
   *
   * @copyright Copyright (c) 2011, iJBlocks Progect
   */
class iJConfig implements iJSingleton {
    
    /**
     *
     * Class Constructuctor
     * 
     * @access public
     */
    public function __construct() {
    //  $this->init();
    }
    
    /**
     *
     * loading config from database
     * 
     * @access public
     */
     
    public function  init() {
      $iJDataBase  =  iJFactory::singleton('iJDataBase');
      $QConfig    =  $iJDataBase->query('SELECT 
                                          configKey, 
                                          configValue 
                                        FROM :table_config
                                        ');
      $QConfig->bindTable(':table_config', TABLE_CONFIG);
      $QConfig->execute();
      
      while($QConfig->next()) {
        if(!defined($QConfig->value('configKey'))) {
          if(strtolower($QConfig->value('configValue')) == 'true') {
            define($QConfig->value('configKey'), true); 
          } else if (strtolower($QConfig->value('configValue')) == 'false'){
            define($QConfig->value('configKey'), false); 
          } else {
            define($QConfig->value('configKey'), $QConfig->value('configValue')); 
          }
          
        }
        
      }
      
    }
    
    /**
     *
     * Return all config variables from database
     * 
     * @param int    $page   - page number
     * @param string $search - search string 
     * @param int    $limt   - result limit
     * 
     * @return config variables
     * @access public
     */
    public function getConfigList($page, $search, $limit = '') {
      $iJDataBase  =  iJFactory::singleton('iJDataBase');
      $QConfig    =  $iJDataBase->query('SELECT 
                                          configKey, 
                                          configValue 
                                        FROM :table_config
                                        ');
      $QConfig->bindTable(':table_config', TABLE_CONFIG);
      
      if(!empty($search)) {
        $QConfig->appendQuery('WHERE configKey like :search');
        $QConfig->bindValue(':search', '%' . $search . '%');
      }
      
      $QConfig->appendQuery(':limit');
      $QConfig->bindTable(':limit', $QConfig->addLimit($page, $limit));
      $QConfig->execute();
      
      $config = array();
      
      while($QConfig->next()) {
        $conf['key']   = $QConfig->value('configKey');
        $conf['value'] = $QConfig->value('configValue');
        $conf['trash'] = iJHrefLink::linkToLocalPage('admin_config') . '?delKey=' . $QConfig->value('configKey');
        $config[] = $conf;
        
      }
      return array($config, $QConfig);
      
    }
    
    
    /**
     *
     * Remove config variable from database
     * 
     * @param string $key - config variable name
     * 
     * @return true is succsess and false if fale
     * @access public
     */
    public function remove($key) {
      $iJDataBase  =  iJFactory::singleton('iJDataBase');
      $QConfig    =  $iJDataBase->query('DELETE FROM :table_config
                                          WHERE configKey = :key
                                        ');
      $QConfig->bindTable(':table_config', TABLE_CONFIG);
      $QConfig->bindValue(':key',          $key);
      $QConfig->execute();
      if(!$iJDataBase->isError()) {
        return true;
      } else {
        return false;
      }
    }
    
    
    /**
     *
     * Add config variable to database
     * 
     * @param string $key   - config variable name
     * @param string $value - config variable value 
     * 
     * @return true is succsess and false if fale
     * @access public
     */
    public function add($key, $value) {
      $iJDataBase  =  iJFactory::singleton('iJDataBase');
      $QConfig    =  $iJDataBase->query('INSERT INTO :table_config
                                                    (
                                                      configKey,
                                                      configValue
                                                    )
                                                    VALUES
                                                    (
                                                      :configKey,
                                                      :configValue
                                                    )
                                        ON DUPLICATE KEY UPDATE 
                                          configValue = :configValue
                                        ');
      $QConfig->bindTable(':table_config', TABLE_CONFIG);
      $QConfig->bindValue(':configKey',          $key);
      $QConfig->bindValue(':configValue',        $value);
      //spr($QConfig);
      $QConfig->execute();
      if(!$iJDataBase->isError()) {
        return true;
      } else {
        return false;
      }
    } 
   
   public function getFileConfig($search) {
    $content   = file_get_contents(CONFIG_PATH);
    
    while (preg_match( "/\n(. )\/\/(.*)\n/isUS" , $content, $matches)) {
      $content = str_replace($matches[0],'',$content);     
    }
    $pattern   = "/\/\*\*(.*)\*(.*)\n/isUS";
    $variables = array();
    while(preg_match($pattern, $content, $matches)) {
      $type = trim($matches[2]);
      //$type = trim($matches[1], '*');
      $content = str_replace($matches[0],'',$content);
      $cut     = strpos($content, '/**');
      if($cut === false) {
        $cut = strlen($content);
      }
      $Vcontent = substr($content, 0, $cut);
      $variables = array_merge($variables, $this->searchVar($Vcontent, $type, $search));
      $content = substr($content, $cut);
      
    }
    return $variables;
   } 
    
    
   public function searchVar($content, $type, $search) {
      $pattern   = "/define\(\'(.*)\);/isUS";
      $variables = array();
      
      while(preg_match($pattern, $content, $matches)) {
         $cut     = strpos($matches[1], '\'');
         $textBef = substr($matches[1], 0, $cut);
         $textAft = substr($matches[1], $cut);
         $comapos = strpos($textAft, ',');
         $var = substr($textAft, $comapos + 1);
         $var = trim($var);
        
         $temp['name']  = $textBef;
         $temp['value'] = $var;
         $temp['type']  = $type;
         $cut     = strpos($content, 'define') + 1;
         $content = substr($content, $cut);
         if ($search != '') {
           if(strpos(strtolower($temp['name']), strtolower($search)) !== false /* || strpos(strtolower($temp['value']), strtolower($search)) !== false*/){
             $variables[] = $temp;
           }
         } else {
           $variables[] = $temp;
         }
         
      }
      
      return $variables;

   }
   
   
 public function delVar($var, $file) {
   $pattern = "/\n(. )define\(\'".$var."'(.*)\);(.*)\n/isUS";
   $content   = file_get_contents($file);
   if(preg_match($pattern, $content, $matches)) {
     $repl =  str_replace($matches[0],'',$content);
     file_put_contents($file,$repl);
     return true;
   } else {return false;}
   
  
 }
    
    
}
?>